# -*- coding: utf-8 -*-


def ws_message(message):
    # ASGI WebSocket packet-received and send-packet message types
    # both have a "text" key for their textual data.
    message.reply_channel.send(
        {
            "text": message.content["text"],
        }
    )


from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.db import database_sync_to_async
from .models import UserNotification


class NotificationConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        if self.scope["user"].is_anonymous:
            await self.close()
            return

        self.user = self.scope["user"]
        self.group_name = f"notify_{self.user.id}"

        # 加入用户专属频道组
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

        # 发送当前未读消息数
        unread = await self.get_unread_count()
        await self.send_json({"type": "unread_count", "count": unread})

    async def disconnect(self, close_code):
        if hasattr(self, "group_name"):
            await self.channel_layer.group_discard(self.group_name, self.channel_name)

    @database_sync_to_async
    def get_unread_count(self):
        return UserNotification.objects.filter(user=self.user, is_read=False).count()

    async def notify_message(self, event):
        """处理真正的消息推送"""
        await self.send_json(event["content"])
